<?php

/**
* http(s)请求代理 操作类 (JS跨域)
*/

class http_proxy {

	protected $max_size = 10485760; // 10 Mb
	protected $allow_type = ['jpg',' jpeg', 'gif', 'png', 'webp'];

	protected $url;
	protected $param = []; // post 数据
	protected $isajax = false;
	protected $files = [];
	protected $root = false;
	//public $method = 'get';
	
	public function __construct() {
		//ini_set('display_errors', 0);
		header("Access-Control-Allow-Origin: *");
		//header('Access-Control-Allow-Headers: X-Requested-With,X_Requested_With'); 
		if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') die; // 跨域文件上传应答
		$this->_checkPostMethod();
	}
	
	public function index() {		
		header('Content-type: text/json');
		$this->_pretreatment();
		$this->_getResult();
	}
	
	protected function _pretreatment() {
		$this->url = trim($_POST['url']);
		//if (preg_match('/https?:[\/]{2}[a-z]+[.]{1}[a-z\d\-]+[.]{1}[a-z\d]*[\/]*[A-Za-z\d]*[\/]*[A-Za-z\d]*[.]*html/U', $this->url)) $this->_error("url format is incorrect [" . $this->url . "]"); // '/^https?\:\/\/(?:[\s\S]+?\.)+/Ui' // 验证url
		$this->param = is_array($_POST['param']) ? $_POST['param'] : [];
		$this->files = $this->_getFiles();
		$this->param['files'] = $this->files;
		//$this->method = trim($_POST['method']) == 'post' ? 'post' : 'get';
		$this->isajax = $_POST['isajax'];
		$this->root = $_POST['hatn'] == 'torn' ? true: false;
	}

	protected function _getFiles() {
		if (!$_FILES) return false;
		$file_arr = [];
		foreach ($_FILES AS $k => $v) {
			if ($v["error"]) $this->_error('[key: ' . $k . '] ' . $v["error"]);
			if ($v['size'] > $this->max_size) $this->_error('[key: ' . $k . '] The maximum size of the file is ' . $this->max_size . ' Mb.');
			$type = strtolower(substr($v['name'], strrpos($v['name'], '.') + 1));
			if (!in_array($type, $this->allow_type)) $this->_error('[key: ' . $k . '] Only allow image files.');
			$file_arr[] = $v["tmp_name"];
		}
		$this->files = $file_arr;
	}

	protected function _getResult() {
		$datas = ['post' => $this->param, 'ajax' => $this->isajax];
		$res = gather($this->url, $datas);
		list($html, $cookie, $header) = $res;
		$json_data = ['success' => true, 'data' => ['html' => $html, 'cookie' => $cookie, 'header' => $header]];
		echo json_encode($json_data, JSON_UNESCAPED_UNICODE);
	}

	protected function _error($str) {
		$json_data = ['error' => $str];
		die(json_encode($json_data, JSON_UNESCAPED_UNICODE));
	}

	protected function _checkPostMethod() {
		if ($_POST) return true;
		header("Content-type: text/html; charset=utf-8");

		$html = <<<EOL
		<title>http(s)请求代理 (JS跨域)</title>
		<link href="https://cdn.bootcss.com/highlight.js/9.12.0/styles/hybrid.min.css" rel="stylesheet">
		<style>
			code { max-width: 1200px; margin: 30px auto; }
		</style>
		<pre>
		<code class="js">
		// http(s)请求代理 (JS跨域)

		// Demo:

		const proxy_api = 'https://www.kon-mio.com/?m=api&c=http_proxy';
		const photo_url = 'https://wall.alphacoders.com/api2.0/get.php?auth=d1f199b2810fb076b72376db7bd2ff95&';

		function func1() {
			$.post(proxy_api, {
					url: photo_url + 'method=search&term=' + encodeURIComponent('girl')
				}, data => {
				let wp = JSON.parse(data.data.html);
				console.log(wp);
			}, 'json');
		}

		function func2() {
			let page = 1;
			$.post(proxy_api, {url: photo_url + 'method=category&id=3&page=' + page}, data => {
				let wp = JSON.parse(data.data.html);
				for (let v of wp.wallpapers) {
					console.log(v.url_image);
				}
			}, 'json');
		}

		function httpProxy(url = '', {param = {}, isajax = 1}, func, func2) {
			return new Promise((resolve, reject) => {
				$.post(proxy_api, {"url": url, "param": param, "isajax": isajax}, data => {
					if (typeof data.success != 'undefined') resolve(data.data);
					reject(data.error);
				}, 'json');
			}).then(data => func(data), data => {
				func2(data);
			});
		}

		httpProxy(photo_url + 'method=search&term=girl', {}, data => console.log(JSON.parse(data.html)), data => console.log(data));

		// ps: 已加载JQ3.3, F12开启控制台可直接测试.
		</code>
		</pre>
		<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
		<script src="https://cdn.bootcss.com/highlight.js/9.12.0/highlight.min.js"></script>
		<script>hljs.initHighlightingOnLoad();</script>
EOL;
		die($html);
	}
}